package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.StandardService;

@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class StandardAction extends ActionSupport implements ModelDriven<Standard> {

	@Autowired
	private StandardService standardService;

	private Standard standard = new Standard();

	@Override
	public Standard getModel() {
		return standard;
	}

	private Integer page;
	private Integer rows;

	public void setPage(Integer page) {
		this.page = page;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}
	
	//添加
	@Action(value = "standard_save", results = {
			@Result(name = "success", location = "pages/base/standard.html", type = "redirect") })
	public String standard_save() {
		standardService.save(standard);
		return SUCCESS;
	}
	
	//分页查询所有
	@Action(value = "standard_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery() throws IOException {
		Pageable pageable = new PageRequest(page -1, rows);

		Page<Standard> pageData = standardService.pageQuery(pageable);

		Map<String, Object> map = new HashMap<>();
		map.put("total", pageData.getTotalElements());
		map.put("rows", pageData.getContent());
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
	
	//删除
	@Action(value="standard_delete",results={@Result(name="success",type="json")})
	public String delete(){
		standardService.delete(standard.getId());
		return SUCCESS;
	}
	
	//异步加载选项
	@Action(value="standard_findAll",results={@Result(name="success",type="json")})
	public String findAll(){
		List<Standard> list = standardService.findAll();
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}
}
